import React from 'react'
// ===================================================================== 
const {  $fn, $Lazy, $http } = window
// ===================================================================== Lazy
const Button 			= $Lazy.load(()=>import('@antd/button'))
const PrinterSetModal 	= $Lazy.state(()=>import('#private/pages/printer-set-modal'),1)
const $time 			= $Lazy.file(()=>import('@com/utils/time'))
const message 			= $Lazy.file(()=>import('@antd/message'))
// =====================================================================
const Index = ({ label='打印', code, way, data, link, disabled, click, hasBtn=true, loading=true, tips }, ref) => {
	const printerRef = React.useRef()
	const onPrinter = React.useCallback( async ( {data, code, link, loading=true} )=>{
		
		const result = typeof data === 'function' ? data() : data
		const _data = await $fn.dataSave('printer')
		let json = []
		let stop = null
		
		if(code === 50106){
			// 报告单打印
			json = result.map(  v => v['spec_num'] )
			window.open(window.globalConfig.api + 'kd-report-spec/toprint?test=1&rno=' + String(json))
		}else{
			if($fn.hasObject(_data) && _data[code].select){
				const { name, select } = _data[code]
				let printer_code = name	// 打印名称
				const printer = select	// 打印模板名称
				
				switch(code){
					case 50103:	// 标本条码号打印
						result.forEach( v => {
							const code = v['new_spec_code'] || v['code']
							const p = { barcode: code, barcodeImg: code, rand:v['rand'] || '', hosp_spec: v['hosp_spec'] || '', printer }
							if(link && $fn.isNumber(link)){		// 判断有无三六九联打印 
								for (let i = 0; i < link; i++) {		
									json.push(p)
								}
							}else{
								json.push(p)
							}
						})
						
						break
					case 50102:	// 标箱打印
						json = result.map( ({ code, box_code }) => ({ barcode: code||box_code, barcodeImg: code||box_code, barlable:'标箱', printer }))
						break
					case 50101:	// 医院客户打印
						json = result.map( ({ hosp_spec, hosp_name }) => ({ barcode: hosp_spec, barcodeImg: hosp_spec, hosp:hosp_name, printer }))
						break
					case 50107:	// 标本架打印
						json = result.map( v => ({ 
							barcode		: v['sf_code'], 
							barcodeImg	: v['sf_code'], 
							gpName		: v['gp_name'],
							projectName	: v['project_name'], 
							sfNumber	: v['sf_number'],
							shelfName	: v['sf_name'],
							printer 
						}))
						break
					case 50104:	// 实验号标签打印
						const time = await $time.then(f => f)
						let noTplitems = []
						result.forEach( v => {
							let date = v.sp_receive_time ? time.full(v.sp_receive_time) : time.full( new Date() )
							const p = { 
								barcode			: $fn.getSplitSpecCode(v.spec_code),
								barcodeImg		: v.spec_code, // 条码号
								station			: v.job_id, // 岗位
								expNo			: v.lb_tpl, // 实验号
								name			: v.patient_name, // 病人姓名
								date			: date.month + '-' + date.day,
								// printNum: this.databox1.search.copies, // 打印数量
								items			: v.kind_name, // 自然项目
								spec_type_name	: v.spec_type_name || '',
								sex				: v.sex_name,
								age				: v.age,
								// tmpl			: v.is_bingli === '1' ? `${printer}.blbarcode` : `${printer}.${printer_code}`,
								tmpl			: `${printer}.${v.tpl_code}`,
								printer,
								third_spec_code	: v.third_spec_code ?? ''
							}
							if($fn.isEmpty(v.tpl_code)){
								noTplitems.push(v.kind_name)
							}else{
								if(link && $fn.isNumber(link)){		// 判断有无三六九联打印
									for (let i = 0; i < link; i++) {		
										json.push(p)
									}
								}else{
									json.push(p)
								}
							}
							stop = true
						})
						/* 根据返回的标签模板分段打印  2021-8-25  --马婷 */
						noTplitems = Array.from(new Set(noTplitems))
						if($fn.hasArray(noTplitems)){
							message.then(f => f.warning(`请先设置项目【${noTplitems.join('，')}】的标签模板`, 2))
						}else{
							let datas = [[]]
							let i = 0
							if($fn.hasArray(json)){
								json.reduce(function(prev, cur) {
									if(!$fn.hasArray(datas[i])){
										datas[i].push(cur)
									}else{
										if( cur.tmpl === prev?.tmpl){
											datas[i].push(cur)
										}else{
											i++
											datas[i] = [cur]
										}
									}
									return cur
								}, json[0])
							}
							datas.forEach( (v, i) => {
								if($fn.hasArray(v)){
									setTimeout(() => {
										$http.submit(null,`http://127.0.0.1:25300/?act=print&tmpl=${v[0].tmpl}`,{
											param:JSON.stringify(v),
											loading,
											noError:true,
											type:0
										})
									}, 500*(i+1) )
								}
							})
						}
						// $http.submit(null,`http://127.0.0.1:25300/?act=print&tmpl=${printer}.${v.tpl_code}`,{
						// 	param:JSON.stringify(json),
						// 	loading,
						// 	noError:true,
						// 	type:0
						// })
						break
					case 50105:	// 肉眼所见打印
						json =  [{ content: result, printer }]
						break
					default:
						break
				}
				if(!stop){
					$http.submit(null,`http://127.0.0.1:25300/?act=print&tmpl=${printer}.${printer_code}`,{
						param:JSON.stringify(json),
						loading,
						noError:true,
						type:0
					})
				}
				click && click?.()
			}else{
				if(tips){
					message.then(f => f.warning('请前往 “设置/设置打印机” 设置【实验号模板】'), 5000)
				}else{
					printerRef.current.refs.ref.open(code)
				}
			}
		}
	},[ tips, click ])
	
	const onClick = React.useCallback( () =>{
		onPrinter({ code, data, link, loading })
	},[ code, data, link, onPrinter, loading ])
	
	React.useImperativeHandle( ref, () => ({
		printer : option => onPrinter(option)
	}))
	
	return (
		<>
			{ hasBtn && <Button label={label} onClick={onClick} disabled={disabled} /> }
			<PrinterSetModal ref={printerRef} />
		</>
	)
}
export default Index